package com.boot.aqs;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Package com.boot.aqs
 */
public class ThreadPoolTester {

    public static void main(String[] args) {
        /*ThreadPoolExecutor(int corePoolSize,
                            int maximumPoolSize,
                            long keepAliveTime,
                            TimeUnit unit,
                            BlockingQueue<Runnable> workQueue,
                            ThreadFactory threadFactory,
                            RejectedExecutionHandler handler)

         SHUTDOWN: 不接受任务 继续执行队列里的任务
         STOP:     不接受任务 队列中的任务不再执行 中断正在执行的线程

         submit  可以接收有返回值的任务
         execute 接收无返回值的任务
        */
        ExecutorService threadPool  = Executors.newFixedThreadPool(4);//ThreadPoolExecutor  core x max x  LinkedBlockingQueue
                        threadPool  = Executors.newCachedThreadPool();// core 0 max  Integer.MAX_VALUE  SynchronousQueue(无容器 内部没有使用AQS，而是直接使用CAS 插入一个元素后生产者被阻塞 消费后被唤醒 生产消费--配对 唤醒分为公平和非公平)
                        threadPool  = Executors.newSingleThreadExecutor();// core 1 max 1 LinkedBlockingQueue
                        threadPool  = Executors.newScheduledThreadPool(10);// core x  max Integer.MAX_VALUE  DelayedWorkQueue
        // CallerRunsPolicy AbortPolicy DiscardPolicy DiscardOldestPolicy
        CountDownLatch count=new CountDownLatch(3);//使用场景 声明资源数 相当于加锁的次数
        Set<String> res =new HashSet<>();
        AtomicInteger num=new AtomicInteger(0);

        for(int i=0;i<5;i++){
            threadPool.execute(()->{
                try {
                    Thread.sleep(2000);
                    res.add(num.incrementAndGet()+"");
                    System.out.println("Thread num="+Thread.currentThread().getId());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count.countDown();
            });
        }

        try {
            count.await();//等待执行完 再取结果
            System.out.println(res);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadPool.shutdown();
    }
}
